const app = getApp();
import { getStorage, setStorage } from "../../utils/localStorage"
import { selectMyDynamics, activity_Registered, getUserInfo, UserDynamics_delete } from "../../api/my";
import { activityGive_option } from "../../api/homePage"
import { baseUrl } from "../../api/request"
import { getMapDistance } from "../../utils/address"
Component({
  data: {
    navData: {
      title: '我的', //导航栏名称
      level: 1 //导航栏级别  
    },
    baseUrl: baseUrl,
    navIndex: 0,
    userInfo: null,
    activityList: [],  //活动列表
    signFlag: null,
    recordList: [],   //列表
    latlng: {}, //经纬度
    townName: null, //乡镇名
    numData: {},
    listQuery: {
      pageNum: 1,
      pageSize: 10,
      userId: Number(getStorage("user").id),
    },
    //列表条件搜索
    pageTop: app.globalData.navHeight + app.globalData.navTop,
    pageBottom: app.globalData.bottomLift - 12,
    tabId: 0,
    triggered: false,
  },
  lifetimes: {
    attached() {
      if (app.loginState()) return;
      this.setData({
        townName: app.globalData.townName.slice(app.globalData.townName.lastIndexOf(",") + 1, app.globalData.townName.length),
        userInfo: getStorage('user'),
      });
      this.setValue();
      this.getActivity_Registered();
      this.getUserInfo();
      this.getDyname();
    },
    detached() {

    },
  },
  pageLifetimes: {
    show: function () {
      this.setData({
        userInfo: getStorage('user'),
      });
      this.getActivity_Registered();
      this.getUserInfo();
    },
  },
  methods: {
    //初始化页面值
    setValue() {
      this.setData({
        baseUrl: baseUrl,
        userInfo: getStorage('user'),
        activityList: [],
        signFlag: null,
        latlng: getStorage('latLng'),
      });
    },
    refresh() {
      this.getActivity_Registered();
      this.getUserInfo();
      this.setData({
        triggered: false,
      })
    },
    //获取已报名活动
    getActivity_Registered() {
      let that = this.data;
      activity_Registered({ userId: that.userInfo.id }).then(res => {
        if (!res.data.data || res.data.data.length === 0) {
          this.setData({
            activityList: []
          });
        } else {
          res.data.data.forEach(item => {
            item.imageScale = item.imageScale.split(",");
            item.distance = getMapDistance(that.latlng.lat, that.latlng.lng, item.latitude, item.longitude);
          });
          this.setData({
            activityList: res.data.data
          });
        };
      });
    },
    //获取关注，粉丝，或赞与收藏数量
    getUserInfo() {
      getUserInfo({ id: this.data.userInfo.id }).then(res => {
        this.setData({
          numData: res.data.data
        });
      });
    },
    //我的卡卷，关注，粉丝，获赞与收场点击事件
    followFansClick(e) {
      let type = e.currentTarget.dataset.type;
      if (type === "我的卡卷") {
        wx.navigateTo({
          url: '/pagesWoDe/pages/cardRoll/index',
        })
      } else if (type === "关注") {
        wx.navigateTo({
          url: '/pagesWoDe/pages/follow/index',
        })
      } else if (type === "粉丝") {
        wx.navigateTo({
          url: '/pagesWoDe/pages/fans/index',
        })
      } else if (type === "获赞与收藏") {
        wx.navigateTo({
          url: '/pagesWoDe/pages/favoredCollection/index',
        })
      };
    },

    //获取乡音列表
    getDyname() {
      selectMyDynamics({ userId: this.data.userInfo.id, tabId: this.data.tabId }).then(res => {
        const arr = res.data.data.map(item => ({
          ...item,
          imageScale: item.imageScale ? item.imageScale.split(",") : []
        }));
        this.setData({
          recordList: arr,
        });
      });
    },

    //删除乡音数据
    remove(e) {
      let item = e.currentTarget.dataset.item;
      wx.showModal({
        title: '动态删除',
        content: '是否确定要删除该条动态',
        complete: (res) => {
          if (res.confirm) {
            UserDynamics_delete({ id: item.id }).then(res => {
              wx.showToast({
                icon: 'none',
                title: res.data.msg,
              });
              this.getDyname();
            })
          };
        }
      })

    },
    //活动列表点赞图标事件
    collectionClick(e) {
      let that = this.data,
        item = e.currentTarget.dataset.item,
        index = e.currentTarget.dataset.index,
        flag = !item.likeState ? true : false;
      activityGive_option({ userId: that.userInfo.id, activityId: item.id, state: flag }).then(res => {
        let state = "activityList[" + index + "].likeState",
          num = "activityList[" + index + "].likeNumber";
        if (res.data.code === 200) {
          this.setData({
            [state]: flag,
            [num]: !flag ? item.likeNumber - 1 : item.likeNumber + 1
          });
        };
      });
    },
    //活动列表点击事件
    activityClick(e) {
      let item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShouYe/pages/bnnerDetailMore/index?id=' + item.id,
      });
    },
    //活动码按钮点击事件
    ActivityCodeTap(e) {
      let item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesWoDe/pages/activityCode/index?id=' + item.id,
      })
    },

    //乡音，收藏，点赞切换点击事件
    navEvent(e) {
      const index = e.currentTarget.dataset.index;
      this.setData({
        navIndex: index,
        tabId: index
      });
      this.getDyname();
    },
    //修改用户信息
    uploadAvart() {
      wx.navigateTo({
        url: '/pagesWoDe/pages/geRenXinxi/index',
      });
    },
    //设置图标事件
    setUp() {
      wx.navigateTo({
        url: '/pagesWoDe/pages/sheZhi/index',
      });
    },
    //购物车按钮点击事件
    shopTap() {
      wx.navigateTo({
        url: '/pagesShangping/pages/index/index',
      });
    },
    //乡音列表点击事件
    xqClick(e) {
      let item = e.currentTarget.dataset.item;
      if (item.mark === "动态") {
        wx.navigateTo({
          url: '/pagesShouYe/pages/listDetail/index?id=' + item.id,
        })
      } else {
        wx.navigateTo({
          url: '/pagesShouYe/pages/bnnerDetailMore/index?id=' + item.id,
        })
      };
    },
    //乡音动态未通过点击事件
    dtUpdate(e) {
      let item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesFaBu/pages/index/index?item=' + encodeURIComponent(JSON.stringify(item)),
      })
    },
    openCollect() {
      let { numData } = this.data;
      if (numData.hasQualification == 0) {
        wx.navigateTo({
          url: '/pagesCollect/pages/reg/step1',
        })
      } else if (numData.hasQualification == 2) {
        wx.navigateTo({
          url: '/pagesCollect/pages/collect/list/list',
        })
      }

    }
  },
})